package cn.com.huzo.webapp.controller.purchase;

import cn.com.huzo.model.entities.purchase.PoHeaderEntity;
import cn.com.huzo.model.entities.purchase.PoLinesEntity;
import cn.com.huzo.model.entities.purchase.PoLinesSurchargesEntity;
import cn.com.huzo.service.master.PurchaseTypeManager;
import huzofw.common.web.controller.BaseFormController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.apache.commons.collections4.MapUtils;
import java.util.ArrayList;
import cn.com.huzo.service.purchase.PoHeaderManager;
import cn.com.huzo.service.purchase.PoLinesManager;
import cn.com.huzo.service.purchase.PoLinesMrpManager;
import cn.com.huzo.service.purchase.PoLinesMrpFeedingManager;
import cn.com.huzo.service.purchase.PoLinesMrpLinesManager;
import cn.com.huzo.service.purchase.PoLinesMrpFeedingLinesManager;
import cn.com.huzo.service.purchase.PoLinesSurchargesManager;
import cn.com.huzo.service.tech.MrpLinesResultManager;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

/**
 * 物料采购订单画面控制器
 *
 * @author 吴旭
 */
@Controller
@RequestMapping(value = "/purchase/po")
public class PoController extends BaseFormController {

    // <editor-fold defaultstate="collapsed" desc="属性">   
    @Resource(name = "freemarkerConfig")
    private FreeMarkerConfigurer freemarkerConfig;

    @Resource(name = "PoHeaderManager")
    private PoHeaderManager _manager_header;

    @Resource(name = "PoLinesManager")
    private PoLinesManager _manager_lines;

    @Resource(name = "PoLinesMrpManager")
    private PoLinesMrpManager _manager_lines_mrp;

    @Resource(name = "PoLinesMrpFeedingManager")
    private PoLinesMrpFeedingManager _manager_lines_mrp_feeding;

    @Resource(name = "PoLinesMrpLinesManager")
    private PoLinesMrpLinesManager _manager_lines_mrp_lines;

    @Resource(name = "PoLinesMrpFeedingLinesManager")
    private PoLinesMrpFeedingLinesManager _manager_lines_mrp_feeding_lines;

    @Resource(name = "PoLinesSurchargesManager")
    private PoLinesSurchargesManager _manager_lines_surcharges;

    @Resource(name = "PurchaseTypeManager")
    private PurchaseTypeManager _manager_purchase_type;

    @Resource(name = "MrpLinesResultManager")
    private MrpLinesResultManager _manager_mrp_lines_result;
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="画面处理部分">
    /**
     * 跳转到物料采购订单一览画面
     * <p>
     * @param request
     * @return
     * @throws java.lang.Exception
     */
    @RequestMapping("/list.html")
    public ModelAndView redirectPoListWnd(HttpServletRequest request) throws Exception {
        ModelAndView view = new ModelAndView();
        view.addObject("PurchaseTypeList", _manager_purchase_type.fetchAll());  // 设置采购类型
        view.setViewName("purchase.po.list.def");
        return view;
    }

    /**
     * 跳转物料采购订单编辑画面
     * <p>
     * @param request 上下文请求
     * @param action 操作类别 1：增加 2：编辑
     * @param poId 采购订单标识
     * @return
     * @throws java.lang.Exception
     */
    @RequestMapping("/{action}/{poId}/edit.html")
    public ModelAndView redirectPoEditWnd(HttpServletRequest request, @PathVariable(value = "action") int action,
            @PathVariable(value = "poId") Long poId) throws Exception {
        ModelAndView view = new ModelAndView();
        // 为画面设置变量
        view.addObject("PurchaseTypeList", _manager_purchase_type.fetchAll());  // 设置采购类型
        view.addObject("action", action);
        view.addObject("poId", poId);
        view.setViewName("purchase.po.edit.def");
        return view;
    }

    /**
     * 跳转到物料采购订单一览画面
     * <p>
     * @param request
     * @return
     * @throws java.lang.Exception
     */
    @RequestMapping("/check.html")
    public ModelAndView redirectPoCheckWnd(HttpServletRequest request) throws Exception {
        ModelAndView view = new ModelAndView();
        view.setViewName("purchase.po.check.def");
        return view;
    }

    /**
     * 跳转物料采购明细的附加费编辑画面
     * <p>
     * @param request
     * @return
     * @throws java.lang.Exception
     */
    @RequestMapping("/lines/surcharges/edit.html")
    public ModelAndView redirectEdit2Wnd(HttpServletRequest request) throws Exception {
        ModelAndView view = new ModelAndView();
        view.setViewName("popup.purchase.po_lines_surcharges.edit.def");
        return view;
    }

    /**
     * 采购订单选择画面（用于非材料花费）
     * <p>
     * @param request
     * @return
     * @throws java.lang.Exception
     */
    @RequestMapping("/choice.html")
    public ModelAndView redirectPoChoiceWnd(HttpServletRequest request) throws Exception {
        ModelAndView view = new ModelAndView();
        view.setViewName("popup.purchase.po.choice.def");
        return view;
    }

    /**
     * 采购订单选择画面（用于采购订单）
     * <p>
     * @param request
     * @return
     * @throws java.lang.Exception
     */
    @RequestMapping("/for_stock_in/choice.html")
    public ModelAndView redirectPoChoiceForStockInWnd(HttpServletRequest request) throws Exception {
        ModelAndView view = new ModelAndView();
        view.setViewName("popup.purchase.po_for_stock_in.choice.def");
        return view;
    }

    /**
     * 订单打印预览画面
     * <p>
     * @return
     */
    @RequestMapping("/print.html")
    public ModelAndView redirectPrintPreviewWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("print.purchase.po.print.def");
        return view;
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="主表-数据处理部分">
    /**
     * 得到新的单据号
     * <p>
     * @return @throws Exception
     */
    @RequestMapping(value = "/header/fetchNewNoOfBill.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchNewBillNo() throws Exception {
        Map<String, Object> rtnVal = new HashMap();
        rtnVal.put("NoOfBill", _manager_header.fetchNewBillNo());
        return rtnVal;
    }

    /**
     * 根据标识取得采购合同数据。
     *
     * @param criterion 采购合同标识
     * @return 采购合同数据（包括主表和子表）。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/header/fetchByKey.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchByKey(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_header.fetchByHeaderKey(criterion);
    }

    /**
     * 根据条件取得采购合同信息分页数据。
     * <p>
     * @param criterion 检索条件
     * @return 采购合同信息分页数据
     * @throws Exception
     */
    @RequestMapping(value = "/header/fetchForPage.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchForPage(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_header.fetchForPage(criterion);
    }

    /**
     * 保存采购合同信息数据。
     * <p>
     * @param instance 要保存的采购合同信息对象。
     * @return 新增记录主键.
     * @throws Exception
     */
    @RequestMapping(value = "/header/save.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Long save(@RequestBody final PoHeaderEntity instance) throws Exception {
        Long rowsAffected;

        if (instance.getHeaderId() > 0) { // 编辑
            rowsAffected = (long) _manager_header.update(instance);
        } else {                          // 新增
            rowsAffected = _manager_header.insert(instance);
        }

        return rowsAffected;
    }

    /**
     * 设置打印次数。
     * <p>
     * @param criterion 订单ID。
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/header/updatePrintFlag.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Integer updatePrintFlag(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_header.updatePrintFlag(MapUtils.getLong(criterion, "PoId"));
    }

    /**
     * 删除采购合同信息数据。
     *
     * @param criterion 要删除的数据
     * @return 返回删除后的数据
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/header/delete.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> delete(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_header.delete(criterion);
    }

    /**
     * 审核。
     * <p>
     * @param criterion 要审核对象。
     * @return 影响行数.
     * @throws Exception
     */
    @RequestMapping(value = "/header/check.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> check(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_header.doCheck(
                MapUtils.getLong(criterion, "HeaderId"),
                MapUtils.getLong(criterion, "WorkFlowId"),
                MapUtils.getShort(criterion, "NodeOrder"),
                MapUtils.getLong(criterion, "CheckedBy"),
                MapUtils.getShort(criterion, "IsCheckCurrentNode"),
                MapUtils.getInteger(criterion, "PageIndex"),
                MapUtils.getInteger(criterion, "Limit")
        );
    }

    /**
     * 反审。
     * <p>
     * @param criterion 要反审对象。
     * @return 影响行数.
     * @throws Exception
     */
    @RequestMapping(value = "/header/uncheck.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> unCheck(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_header.doUnCheck(
                MapUtils.getLong(criterion, "HeaderId"),
                MapUtils.getLong(criterion, "WorkFlowId"),
                MapUtils.getShort(criterion, "NodeOrder"),
                MapUtils.getLong(criterion, "CheckedBy"),
                MapUtils.getInteger(criterion, "PageIndex"),
                MapUtils.getInteger(criterion, "Limit")
        );
    }

    /**
     * 审核数据。
     * <p>
     * @param criterion 要审核对象。
     * @return 审核后的数据
     * @throws Exception
     */
    @RequestMapping(value = "/header/batchCheck.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> batchCheck(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_header.batchCheck(criterion);

    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="明细-引入物料需求计划数据处理部分">
    /**
     * 根据条件取得引入的调达表明细分页数据。
     * <p>
     * @param criterion 检索条件
     * @return 采购合同信息分页数据
     * @throws Exception
     */
    @RequestMapping(value = "/lines/mrp/fetchForPage.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchLinesMrpForPage(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_lines_mrp_lines.fetchForPage(criterion);
    }

    /**
     * 根据条件取得引入的补料单明细分页数据。
     * <p>
     * @param criterion 检索条件
     * @return 采购合同信息分页数据
     * @throws Exception
     */
    @RequestMapping(value = "/lines/mrp/feeding/fetchForPage.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchLinesMrpFeedingForPage(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_lines_mrp_feeding_lines.fetchForPage(criterion);
    }

    /**
     * 通过引入调达表，新增采购合同明细信息数据。
     * <p>
     * @param criterion 引用的调达表、各个明细显示的记录数
     * @return 新增记录主键.
     * @throws Exception
     */
    @RequestMapping(value = "/lines/mrp/insert.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> insertLinesMrp(@RequestBody final Map<String, Object> criterion) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        List<Long> mrpHeaderKeyList = mapper.convertValue(MapUtils.getObject(criterion, "MrpHeaderId"), new TypeReference<List<Long>>() {
        });
        List<String> mrpLinesKeyList;

        if (MapUtils.getInteger(criterion, "SelectAllFlag") == 1) {
            criterion.put("HeaderIdList", mrpHeaderKeyList);
            mrpLinesKeyList = _manager_mrp_lines_result.fetchAllSelectedLines(criterion);
        } else {
            mrpLinesKeyList = mapper.convertValue(MapUtils.getObject(criterion, "MrpLinesId"), new TypeReference<List<String>>() {
            });
        }

        return _manager_lines_mrp.insertLines(
                MapUtils.getLong(criterion, "HeaderId"),
                MapUtils.getLong(criterion, "UpdatedBy"),
                mrpHeaderKeyList,
                mrpLinesKeyList,
                MapUtils.getShort(criterion, "SeparateFlagByPartOfNeed"),
                MapUtils.getInteger(criterion, "Limit02"),
                MapUtils.getInteger(criterion, "Limit04"),
                MapUtils.getString(criterion, "PoNo"));
    }

    /**
     * 通过引入补料单，新增采购合同明细信息数据。
     * <p>
     * @param criterion 引用的补料单、各个明细显示的记录数
     * @return 新增记录主键.
     * @throws Exception
     */
    @RequestMapping(value = "/lines/mrp/feeding/insert.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> insertLinesMrpFeeding(@RequestBody final Map<String, Object> criterion) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        List<Long> mrpFeedingHeaderKeyList = mapper.convertValue(MapUtils.getObject(criterion, "MrpFeedingHeaderId"), new TypeReference<List<Long>>() {
        });
        List<String> mrpFeedingLinesKeyList = mapper.convertValue(MapUtils.getObject(criterion, "MrpFeedingLinesId"), new TypeReference<List<String>>() {
        });

        return _manager_lines_mrp_feeding.insertLines(
                MapUtils.getLong(criterion, "HeaderId"),
                MapUtils.getLong(criterion, "UpdatedBy"),
                mrpFeedingHeaderKeyList,
                mrpFeedingLinesKeyList,
                MapUtils.getShort(criterion, "SeparateFlagByPartOfNeed"),
                MapUtils.getInteger(criterion, "Limit02"),
                MapUtils.getInteger(criterion, "Limit04"),
                MapUtils.getString(criterion, "PoNo"));
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="订单明细数据处理部分">
    /**
     * 根据条件取得采购订单明细分页数据。
     * <p>
     * @param criterion 检索条件
     * @return 采购合同信息分页数据
     * @throws Exception
     */
    @RequestMapping(value = "/lines/fetchForPage.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchLinesForPage(@RequestBody Map<String, Object> criterion) throws Exception {
        return _manager_lines.fetchForPage(criterion);
    }

    /**
     * 根据选择的订单取得明细分页数据。
     * <p>
     * @param criterion 检索条件
     * @return 订单明细分页数据
     * @throws Exception
     */
    @RequestMapping(value = "/lines/fetchForPageByPoNo.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchLinesForPageByPoNo(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_lines.fetchForPageByPoNo(criterion);
    }

    /**
     * 更改采购合同明细信息数据。
     * <p>
     * @param criterion 要更新的订单明细数据以及当前分页情况
     * @return 更新后的订单明细
     * @throws Exception
     */
    @RequestMapping(value = "/lines/update.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> updateLines(@RequestBody final Map<String, Object> criterion) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        List<PoLinesEntity> _updatedLinesList = mapper.convertValue(MapUtils.getObject(criterion, "UpdatedLinesList"), new TypeReference<List<PoLinesEntity>>() {
        });

        if (_updatedLinesList.isEmpty()) {
            Map<String, Object> _result = new HashMap();
            _result.put("Success", false);
            return _result;
        } else {
            return _manager_lines.updateLines(
                    MapUtils.getLong(criterion, "HeaderId"),
                    MapUtils.getLong(criterion, "UpdatedBy"),
                    MapUtils.getLong(criterion, "CurrentUserId"),
                    MapUtils.getInteger(criterion, "Limit"),
                    MapUtils.getInteger(criterion, "PageIndex"),
                    MapUtils.getString(criterion, "OrderBy"),
                    _updatedLinesList);
        }
    }

    /**
     * 更改订单材料
     * <p>
     * @param criterion 要更新的订单明细数据以及当前分页情况
     * @return 更新后的订单明细
     * @throws Exception
     */
    @RequestMapping(value = "/lines/updateRowMaterial.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> updateRowMaterial(@RequestBody final Map<String, Object> criterion) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        List<PoLinesEntity> _updatedLinesList = mapper.convertValue(MapUtils.getObject(criterion, "UpdatedLinesList"), new TypeReference<List<PoLinesEntity>>() {
        });

        if (_updatedLinesList.isEmpty()) {
            Map<String, Object> _result = new HashMap();
            _result.put("Success", false);
            return _result;
        } else {
            return _manager_lines.updateRowMaterial(
                    MapUtils.getLong(criterion, "HeaderId"),
                    MapUtils.getLong(criterion, "UpdatedBy"),
                    MapUtils.getLong(criterion, "CurrentUserId"),
                    MapUtils.getInteger(criterion, "Limit02"),
                    MapUtils.getInteger(criterion, "Limit03"),
                    MapUtils.getInteger(criterion, "Limit04"),
                    MapUtils.getInteger(criterion, "PageIndex04"),
                    MapUtils.getString(criterion, "OrderBy"),
                    _updatedLinesList);
        }
    }

    /**
     * 删除采购合同明细。
     *
     * @param criterion 要删除的数据以及当前分页情况
     * @return 删除后的订单明细及相关引入数据。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/delete.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> deleteLines(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_lines.deleteLines(
                MapUtils.getString(criterion, "LinesId"),
                MapUtils.getLong(criterion, "HeaderId"),
                MapUtils.getLong(criterion, "DeletedBy"),
                MapUtils.getLong(criterion, "CurrentUserId"),
                MapUtils.getInteger(criterion, "Limit02"),
                MapUtils.getInteger(criterion, "Limit03"),
                MapUtils.getInteger(criterion, "Limit04"),
                MapUtils.getInteger(criterion, "PageIndex04"),
                MapUtils.getString(criterion, "OrderBy"));
    }

    /**
     * 批量删除明细信息数据。
     *
     * @param criterion 批量删除的数据以及当前分页情况数据
     * @return 删除后的订单明细及相关引入数据。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/batch_delete.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> batchDeleteLines(@RequestBody final Map<String, Object> criterion) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        List<PoLinesEntity> _deletedLinesList = mapper.convertValue(MapUtils.getObject(criterion, "DeletedLinesList"), new TypeReference<List<PoLinesEntity>>() {
        });

        if (_deletedLinesList.isEmpty()) {
            Map<String, Object> _result = new HashMap();
            _result.put("Success", false);
            return _result;
        } else {
            return _manager_lines.batchDeleteLines(
                    MapUtils.getLong(criterion, "HeaderId"),
                    MapUtils.getLong(criterion, "DeletedBy"),
                    MapUtils.getLong(criterion, "CurrentUserId"),
                    MapUtils.getInteger(criterion, "Limit02"),
                    MapUtils.getInteger(criterion, "Limit03"),
                    MapUtils.getInteger(criterion, "Limit04"),
                    MapUtils.getInteger(criterion, "PageIndex04"),
                    MapUtils.getString(criterion, "OrderBy"),
                    _deletedLinesList);
        }
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="附加费数据处理部分">
    /**
     * 得到全部附加费数据列表
     *
     * @param headerId 采购订单ID
     * @return 全部附加费数据列表
     * @throws java.lang.Exception
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/lines/surcharges/fetchAll.html",
            method = RequestMethod.POST)
    public @ResponseBody
    List<PoLinesSurchargesEntity> fetchAllSurchargesByHeaderId(@RequestBody final Long headerId) throws Exception {
        return _manager_lines_surcharges.fetchAllByHeaderId(headerId);
    }

    /**
     * 批量保存或更新附加费。
     *
     * @param criterion 要处理的附加费数据列表
     * @return
     *
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/surcharges/save.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> save(@RequestBody final Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();

        ObjectMapper mapper = new ObjectMapper();
        List<PoLinesSurchargesEntity> insertItemList = mapper.convertValue(MapUtils.getObject(criterion, "InsertList"), new TypeReference<List<PoLinesSurchargesEntity>>() {
        });
        List<PoLinesSurchargesEntity> updateItemList = mapper.convertValue(MapUtils.getObject(criterion, "UpdateList"), new TypeReference<List<PoLinesSurchargesEntity>>() {
        });

        if (insertItemList.size() > 0) {
            _result = _manager_lines_surcharges.insert(
                    MapUtils.getLong(criterion, "HeaderId"),
                    MapUtils.getInteger(criterion, "Limit"),
                    MapUtils.getInteger(criterion, "PageIndex"),
                    insertItemList);
        }
        if (updateItemList.size() > 0) {
            _result = _manager_lines_surcharges.update(
                    MapUtils.getLong(criterion, "HeaderId"),
                    MapUtils.getInteger(criterion, "Limit"),
                    MapUtils.getInteger(criterion, "PageIndex"),
                    updateItemList);
        }

        return _result;
    }

    /**
     * 删除附加费。
     *
     * @param criterion 要删除的数据
     * <p>
     * @return
     *
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/surcharges/delete.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> deleteSurcharges(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_lines_surcharges.delete(
                MapUtils.getLong(criterion, "HeaderId"),
                MapUtils.getString(criterion, "LinesId"),
                MapUtils.getLong(criterion, "DeletedBy"),
                MapUtils.getString(criterion, "PoNo"),
                MapUtils.getString(criterion, "Desctiption"),
                MapUtils.getInteger(criterion, "Limit"),
                MapUtils.getInteger(criterion, "PageIndex"));
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="数据补全处理部分">
    /**
     * 根据输入的订单号从采购订单中补齐剩余部分
     *
     * @param criterion 部分订单号
     * @return 补全的订单号列表
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/fetchPoNoForAutoComplate.html",
            method = RequestMethod.POST)
    public @ResponseBody
    List<String> fetchPoNoForAutoComplate(@RequestBody final Map<String, Object> criterion) throws Exception {
        if (criterion.get("keyword") != null) {
            return _manager_header.fetchPoNoForAutoComplate(MapUtils.getString(criterion, "keyword"));
        } else {
            return new ArrayList();
        }
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="打印处理部分">
    /**
     * 打印预览。
     *
     * @param criterion 标识等
     * @return 物料需求计划数据。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/fetchPrintPreviewData.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchPrintPreviewData(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_header.fetchPrintPreviewData(criterion);
    }

    /**
     * 导出订单各款圆卡类使用明细
     *
     * @param response 客户端响应
     * @param request 客户端请求
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/export_memo_to_excel.html",
            method = RequestMethod.POST)
    public void exportMemoToExcel(HttpServletResponse response, HttpServletRequest request) throws Exception {
        long _poHeaderId = Long.parseLong(request.getParameter("_ExportPoHeaderId").trim());
        Map<String, Object> criterion = new HashMap();
        criterion.put("PoHeaderId", _poHeaderId);
        Map<String, Object> data = _manager_header.fetchExportMemoData(criterion);

        String filename = "订单各款纸卡类使用明细表.xls";

        try (OutputStream out = response.getOutputStream()) {
            response.reset();                                                   // 清空输出流
            response.setHeader("Content-disposition", "attachment; filename="
                    + new String(filename.getBytes("GB2312"), "ISO8859-1"));    // 设定输出文件头
            response.setContentType("application/msexcel");                     // 定义输出类型

            /**
             * **********创建工作簿************
             */
            parse("03_purchase/订单各款纸卡类使用明细表.ftl", data, out);
            out.flush();
        }
    }

    private void parse(String templateName, Map<String, Object> data, OutputStream out) throws IOException, TemplateException {
        try (OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8")) {
            Configuration cfg = freemarkerConfig.getConfiguration();
            // 加载模板
            Template template = cfg.getTemplate(templateName, "utf-8");
            // 填充数据至Excel
            template.process(data, writer);
            writer.flush();
        }
    }
    // </editor-fold>
}
